import os
import re
import logging
from logging.handlers import TimedRotatingFileHandler

from masoniteorm.connections import ConnectionResolver

from .app import appSettings

DATABASES = {
    "default": "mysql",

    "mysql": {
        "host": appSettings.db_host,
        "driver": appSettings.db_type,
        "database": appSettings.db_name,
        "user": appSettings.db_user,
        "password": appSettings.db_pass,
        "port": appSettings.db_port,
        "log_queries": appSettings.db_log,
        "options": {
            #
        }
    },

    "postgres": {
        "host": appSettings.db_code_host,
        "driver": appSettings.db_code_type,
        "database": appSettings.db_code_name,
        "user": appSettings.db_code_user,
        "password": appSettings.db_code_pass,
        "port": appSettings.db_code_port,
        "prefix": appSettings.db_code_prefix,
        "log_queries": appSettings.db_code_log,
        "options": {
            #
        }
    },
}


DB = ConnectionResolver().set_connection_details(DATABASES)

# 获取日志
logger = logging.getLogger('masoniteorm.connection.queries')
logger.setLevel(logging.DEBUG)

# 终端显示
handler = logging.StreamHandler()

# 保存到文件中
sql_log_path = os.path.join(appSettings.log_path, 'sql')
if not os.path.exists(sql_log_path):
    os.makedirs(sql_log_path)
log_file_path = os.path.join(sql_log_path, 'queries')
# file_handler = logging.FileHandler(log_file_path)
file_handler = TimedRotatingFileHandler(
    filename=log_file_path, when="MIDNIGHT", interval=1, backupCount=30
)
# filename="mylog" suffix设置，会生成文件名为mylog.2020-02-25.log
file_handler.suffix = "%Y-%m-%d.log"
# extMatch是编译好正则表达式，用于匹配日志文件名后缀
# 需要注意的是suffix和extMatch一定要匹配的上，如果不匹配，过期日志不会被删除。
file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
# 定义日志输出格式
file_handler.setFormatter(
    logging.Formatter(
        "[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s"
    )
)

# 注册日志收集器
logger.addHandler(handler)
logger.addHandler(file_handler)
